#!/bin/bash
# 服务监控脚本V2.0 - 带通知开关控制

# 配置区
declare -A SERVICE_MAP=(
    ["nginx"]="nginx:worker"
    ["mysqld"]="mysqld" 
    ["mysql"]="mysqld"
    ["redis-server"]="redis-server"
)
# 日志配置
LOG_FILE="/var/log/service_monitor.log"
MAX_LOG_SIZE=1048576  # 1MB轮转
# 通知配置
WEBHOOK_URL="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=yourkey"
NOTIFY_ENABLED=true  # 默认开启通知

# 日志轮转检查
if [[ -f "$LOG_FILE" && $(stat -c%s "$LOG_FILE") -gt $MAX_LOG_SIZE ]]; then
    mv "$LOG_FILE" "${LOG_FILE}.$(date +%Y%m%d%H%M)"
fi

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        --disable-notify)
            NOTIFY_ENABLED=false
            shift
            ;;
        -e|--env-file)
            source "$2"
            shift 2
            ;;
        *)
            echo "未知参数: $1"
            exit 1
            ;;
    esac
done

# 发送通知函数
send_notify() {
    local level="$1"
    local message="$2"
    
    if [[ $NOTIFY_ENABLED == true ]]; then
        local color=$([[ "$level" == "CRITICAL" ]] && echo "FF0000" || echo "008000")
        curl -s -H "Content-Type: application/json" \
        -d "{
            \"msgtype\":\"markdown\",
            \"markdown\":{
                \"content\":\"<font color=\\\"$color\\\">【服务监控】</font> \n
                > 级别：$level \n
                > 时间：$(date '+%F %T')\n
                > 详情：$message\"
            }
        }" "$WEBHOOK_URL" >/dev/null
    fi
}

{
    echo "====== 服务监控开始 [通知开关: ${NOTIFY_ENABLED}] ======"
    
    for SERVICE_UNIT in "${!SERVICE_MAP[@]}"; do
        # 检测服务是否部署
        if ! systemctl list-unit-files | grep -q "^${SERVICE_UNIT}.service"; then
            echo "[INFO] $SERVICE_UNIT 服务未安装，跳过检测"
            continue
        fi
        
        # 检查服务活性状态
        if systemctl is-active "$SERVICE_UNIT" >/dev/null; then
            # 二次验证进程是否存在（防止systemd状态延迟）
            if pgrep -f "$PROCESS_PATTERN" >/dev/null; then
                echo "[OK] $SERVICE_UNIT 运行正常 (PID: $(pgrep -f "$PROCESS_PATTERN"))"
            else
                echo "[WARN] $SERVICE_UNIT systemd状态异常，尝试恢复..."
                systemctl reset-failed "$SERVICE_UNIT"
                systemctl restart "$SERVICE_UNIT"
            fi
        else
            echo "[ERROR] $SERVICE_UNIT 服务未运行! 尝试紧急重启..."
            if systemctl restart "$SERVICE_UNIT"; then
                echo "[OK] $SERVICE_UNIT 重启成功"
                # 发送企业微信通知
                send_notify "INFO" "$SERVICE_UNIT 已成功重启"
            else
                echo "[CRITICAL] $SERVICE_UNIT 重启失败! 请人工介入!"
                # 触发告警升级
                send_notify "CRITICAL" "$SERVICE_UNIT 重启失败，需要人工介入！"
            fi
        fi
    done
    echo "====== 监控结束 [耗时：${SECONDS}s] ======"
} | tee -a "$LOG_FILE"